package com.example.comic.mvp.view

import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import com.example.comic.R
import com.example.comic.mvp.model.Pager
import com.example.comic.mvp.ppresenter.PagePresenter
import kotlinx.android.synthetic.main.content_main.*
import org.jetbrains.anko.async
import org.jetbrains.anko.uiThread

class PagerActivity : AppCompatActivity() {
    companion object {
        val INTENT_LINK = "link"
    }

    lateinit var link: String
    lateinit var adapter: PageAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_pager)
        link = intent.getStringExtra(INTENT_LINK)
    }

    override fun onResume() {
        super.onResume()
        async {
            val data = PagePresenter().obtain(link)
            uiThread {
                initView(data)
            }
        }
    }

    private fun initView(data: ArrayList<Pager.DataBean.ReturnDataBean.ImageListBean>) {
        adapter = PageAdapter(data, supportFragmentManager)
        viewPager.adapter = adapter
        viewPager.offscreenPageLimit = 2

    }

    class PageAdapter(var data: ArrayList<Pager.DataBean.ReturnDataBean.ImageListBean>, fragmentManager: FragmentManager) : FragmentPagerAdapter(fragmentManager) {
        override fun getCount(): Int = data.size
        override fun getItem(position: Int): Fragment = PageFragment.newInstance(data[position].location)

    }
}
